package com.xxx.generator.util;


import com.xxx.generator.common.entity.ColumnEntity;
import com.xxx.generator.common.entity.TableEntity;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.*;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成器   工具类
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年12月19日 下午11:40:24
 */
public class NewGenUtils {

    public static List<String> getTemplates() {
        List<String> templates = new ArrayList<String>();
        templates.add("new-template/Controller.java.vm");
        templates.add("new-template/Converter.java.vm");
        templates.add("new-template/Dao.java.vm");
        templates.add("new-template/Dao.xml.vm");
        templates.add("new-template/DO.java.vm");
        templates.add("new-template/Service.java.vm");
        templates.add("new-template/ServiceImpl.java.vm");
        templates.add("new-template/VO.java.vm");
        templates.add("new-template/PageQuery.java.vm");

        return templates;
    }

    public static List<String> getInitTemplates() {
        List<String> templates = new ArrayList<String>();

        templates.add("new-template/init/project.pom.vm");
        templates.add("new-template/init/app/App.pom.vm");
        templates.add("new-template/init/app/App.java.vm");
        templates.add("new-template/init/app/App.yml.vm");

        templates.add("new-template/init/common/common.pom.vm");
        templates.add("new-template/init/common/cache/common.cache.pom.vm");
        templates.add("new-template/init/common/cache/CacheNames.java.vm");
        templates.add("new-template/init/common/cache/RedisCacheConfig.java.vm");

        templates.add("new-template/init/common/core/common.core.pom.vm");
        templates.add("new-template/init/common/core/AopConfig.java.vm");
        templates.add("new-template/init/common/core/Constants.java.vm");
        templates.add("new-template/init/common/core/Exception.java.vm");
        templates.add("new-template/init/common/core/ExceptionHandler.java.vm");
        templates.add("new-template/init/common/core/IsDeleted.java.vm");
        templates.add("new-template/init/common/core/MvcConfig.java.vm");
        templates.add("new-template/init/common/core/PageQuery.java.vm");
        templates.add("new-template/init/common/core/R.java.vm");
        templates.add("new-template/init/common/core/Response.java.vm");
        templates.add("new-template/init/common/core/Swagger.java.vm");
        templates.add("new-template/init/common/core/ThreadPool.java.vm");
        templates.add("new-template/init/common/core/YesOrNo.java.vm");

        templates.add("new-template/init/common/db/common.db.pom.vm");
        templates.add("new-template/init/common/db/BaseDO.java.vm");
        templates.add("new-template/init/common/db/DbConfig.java.vm");
        templates.add("new-template/init/common/db/PageVO.java.vm");

        return templates;
    }

    /**
     * 生成代码
     */
    public static void generatorCode(Map<String, String> table, List<Map<String, String>> columns, ZipOutputStream zip, boolean isInit) {
        //配置信息
        Configuration config = getConfig();
        boolean hasBigDecimal = false;
        boolean hasList = false;
        //表信息
        TableEntity tableEntity = new TableEntity();
        tableEntity.setTableName(table.get("tableName"));
        tableEntity.setComments(table.get("tableComment"));
        //表名转换成Java类名
        String className = tableToJava(tableEntity.getTableName(), config.getStringArray("tablePrefix"));
        tableEntity.setClassName(className);
        tableEntity.setClassname(StringUtils.uncapitalize(className));

        //列信息
        List<ColumnEntity> columsList = new ArrayList<>();
        for (Map<String, String> column : columns) {
            ColumnEntity columnEntity = new ColumnEntity();
            columnEntity.setColumnName(column.get("columnName"));
            columnEntity.setDataType(column.get("dataType"));
            columnEntity.setComments(column.get("columnComment"));
            columnEntity.setExtra(column.get("extra"));
            columnEntity.setNullable(Objects.equals("YES", column.get("isNullable")));

            //列名转换成Java属性名
            String attrName = columnToJava(columnEntity.getColumnName());
            columnEntity.setAttrName(attrName);
            columnEntity.setAttrname(StringUtils.uncapitalize(attrName));

            //列的数据类型，转换成Java类型
            String attrType = config.getString(columnEntity.getDataType(), columnToJava(columnEntity.getDataType()));
            columnEntity.setAttrType(attrType);

            if (!hasBigDecimal && attrType.equals("BigDecimal")) {
                hasBigDecimal = true;
            }
            if (!hasList && "array".equals(columnEntity.getExtra())) {
                hasList = true;
            }
            //是否主键
            if ("PRI".equalsIgnoreCase(column.get("columnKey")) && tableEntity.getPk() == null) {
                tableEntity.setPk(columnEntity);
            }

            columsList.add(columnEntity);
        }
        tableEntity.setColumns(columsList);

        //没主键，则第一个字段为主键
        if (tableEntity.getPk() == null) {
            tableEntity.setPk(tableEntity.getColumns().get(0));
        }

        //设置velocity资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);
        String mainPath = config.getString("mainPath");
        mainPath = StringUtils.isBlank(mainPath) ? "io.renren" : mainPath;
        String projectname = config.getString("projectname");
        String moduleName = config.getString("moduleName");
        String ModuleName = Character.toUpperCase(moduleName.charAt(0)) + moduleName.substring(1);
        String ProjectName = Character.toUpperCase(projectname.charAt(0)) + projectname.substring(1);
        //封装模板数据
        Map<String, Object> map = new HashMap<>();
        map.put("tableName", tableEntity.getTableName());
        map.put("comments", tableEntity.getComments());
        map.put("pk", tableEntity.getPk());
        map.put("className", tableEntity.getClassName());
        map.put("classname", tableEntity.getClassname());
        map.put("pathName", tableEntity.getClassname().toLowerCase());
        map.put("columns", tableEntity.getColumns());
        map.put("hasBigDecimal", hasBigDecimal);
        map.put("hasList", hasList);
        map.put("mainPath", mainPath);
        map.put("swaggerEnable", config.getBoolean("swaggerEnable"));
        map.put("projectname", config.getString("projectname"));
        map.put("groupId", config.getString("groupId"));
        map.put("ProjectName", ProjectName);
        map.put("package", config.getString("package"));
        map.put("moduleName", config.getString("moduleName"));
        map.put("ModuleName", ModuleName);
        map.put("author", config.getString("author"));
        map.put("email", config.getString("email"));
        map.put("datetime", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
        VelocityContext context = new VelocityContext(map);

        //获取模板列表
        List<String> templates = getTemplates();
        if (isInit) {
            List<String> initTemplates = getInitTemplates();
            for (String template : initTemplates) {
                //渲染模板
                StringWriter sw = new StringWriter();
                Template tpl = Velocity.getTemplate(template, "UTF-8");
                tpl.merge(context, sw);

                try {
                    //添加到zip
                    zip.putNextEntry(new ZipEntry(getInitFileName(template, tableEntity.getClassName(), config.getString("projectname"), mainPath, config.getString("moduleName"))));
                    IOUtils.write(sw.toString(), zip, "UTF-8");
                    IOUtils.closeQuietly(sw);
                    zip.closeEntry();
                } catch (IOException e) {
                    throw new RuntimeException("渲染模板失败，表名：" + tableEntity.getTableName(), e);
                }
            }
        }
        for (String template : templates) {
            //渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, "UTF-8");
            tpl.merge(context, sw);

            try {
                //添加到zip
                zip.putNextEntry(new ZipEntry(getFileName(template, tableEntity.getClassName(), config.getString("projectname"), mainPath, config.getString("moduleName"))));
                IOUtils.write(sw.toString(), zip, "UTF-8");
                IOUtils.closeQuietly(sw);
                zip.closeEntry();
            } catch (IOException e) {
                throw new RuntimeException("渲染模板失败，表名：" + tableEntity.getTableName(), e);
            }
        }
    }


    /**
     * 列名转换成Java属性名
     */
    public static String columnToJava(String columnName) {
        return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "");
    }

    /**
     * 表名转换成Java类名
     */
    public static String tableToJava(String tableName, String[] tablePrefixArray) {
        if (null != tablePrefixArray && tablePrefixArray.length > 0) {
            for (String tablePrefix : tablePrefixArray) {
                if (tableName.startsWith(tablePrefix)) {
                    tableName = tableName.replaceFirst(tablePrefix, "");
                }
            }
        }
        return columnToJava(tableName);
    }

    /**
     * 获取配置信息
     */
    public static Configuration getConfig() {
        try {
            return new PropertiesConfiguration("generator.properties");
        } catch (ConfigurationException e) {
            throw new RuntimeException("获取配置文件失败，", e);
        }
    }

    /**
     * 获取文件名
     */
    public static String getFileName(String template, String className, String projectname, String packageName, String moduleName) {
        //template\template-server\src
        String packagePath = projectname + File.separator + projectname + "-" + moduleName + File.separator + "src/main" + File.separator + "java" + File.separator;
        String resourcePath = projectname + File.separator + projectname + "-" + moduleName + File.separator + "src/main" + File.separator + "resources" + File.separator;
        if (StringUtils.isNotBlank(packageName)) {
            packagePath += packageName.replace(".", File.separator) + File.separator + moduleName + File.separator;
        }
        if (template.contains("DO.java.vm")) {
            return packagePath + "domain/model" + File.separator + className + ".java";
        }
        if (template.contains("VO.java.vm")) {
            return packagePath + "domain/vo" + File.separator + className + "VO.java";
        }
        if(template.contains("PageQuery.java.vm")){
            return packagePath + "domain/vo/query" + File.separator + className + "PageQuery.java";
        }
        if (template.contains("Dao.java.vm")) {
            return packagePath + "mapper" + File.separator + className + "Mapper.java";
        }

        if (template.contains("Service.java.vm")) {
            return packagePath + "service" + File.separator + className + "Service.java";
        }

        if (template.contains("ServiceImpl.java.vm")) {
            return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java";
        }

        if (template.contains("Controller.java.vm")) {
            return packagePath + "api" + File.separator + className + "Api.java";
        }
        if (template.contains("Converter.java.vm")) {
            return packagePath + "converter" + File.separator + className + "Converter.java";
        }
        if (template.contains("Dao.xml.vm")) {
            return resourcePath + "mapper" + File.separator + moduleName + File.separator + className + "Mapper.xml";
        }



        return null;
    }

    public static String getInitFileName(String template, String className, String projectname, String packageName, String moduleName) {
        //template\template-server\src
        String projectPath = projectname + File.separator;
        String commonPath = projectPath + projectname + "-common" + File.separator;
        String commonCachePath = projectPath + projectname + "-common" + File.separator + projectname + "-common-cache" + File.separator;
        String commonCorePath = projectPath + projectname + "-common" + File.separator + projectname + "-common-core" + File.separator;
        String commonDbPath = projectPath + projectname + "-common" + File.separator + projectname + "-common-database" + File.separator;
        String appPath = projectPath + projectname + "-" + moduleName + File.separator;
        String packagePath = "src/main/java" + File.separator + packageName.replace(".", File.separator) + File.separator;
        String ModuleName = Character.toUpperCase(moduleName.charAt(0)) + moduleName.substring(1);
        String ProjectName = Character.toUpperCase(projectname.charAt(0)) + projectname.substring(1);
        if (template.contains("project.pom.vm")) {
            return projectPath + "pom.xml";
        }
        if (template.contains("App.pom.vm")) {
            return appPath + "pom.xml";
        }
        if (template.contains("common.pom.vm")) {
            return commonPath + "pom.xml";
        }
        if (template.contains("common.cache.pom.vm")) {
            return commonCachePath + "pom.xml";
        }
        if (template.contains("common.core.pom.vm")) {
            return commonCorePath + "pom.xml";
        }
        if (template.contains("common.db.pom.vm")) {
            return commonDbPath + "pom.xml";
        }
        if (template.contains("App.java.vm")) {
            return appPath + packagePath + ModuleName + "App.java";
        }
        if (template.contains("App.yml.vm")) {
            return appPath + "src/main/resources/application.yml";
        }
        if (template.contains("CacheNames.java.vm")) {
            return commonCachePath + packagePath + File.separator + "constants/CacheNames.java";
        }
        if (template.contains("RedisCacheConfig.java.vm")) {
            return commonCachePath + packagePath + File.separator + "config/RedisCacheConfig.java";
        }
        //core
        if (template.contains("AopConfig.java.vm")) {
            return commonCorePath + packagePath + File.separator + "config/AopConfig.java";
        }
        if (template.contains("MvcConfig.java.vm")) {
            return commonCorePath + packagePath + File.separator + "config/MvcConfig.java";
        }
        if (template.contains("Swagger.java.vm")) {
            return commonCorePath + packagePath + File.separator + "config/SwaggerConfiguration.java";
        }
        if (template.contains("ThreadPool.java.vm")) {
            return commonCorePath + packagePath + File.separator + "config/ThreadPoolConfig.java";
        }
        if (template.contains("Constants.java.vm")) {
            return commonCorePath + packagePath + File.separator + "constants/Constants.java";
        }
        if (template.contains("IsDeleted.java.vm")) {
            return commonCorePath + packagePath + File.separator + "constants/enums/IsDeletedEnum.java";
        }
        if (template.contains("YesOrNo.java.vm")) {
            return commonCorePath + packagePath + File.separator + "constants/enums/YesOrNoEnum.java";
        }
        if (template.contains("R.java.vm")) {
            return commonCorePath + packagePath + File.separator + "core/R.java";
        }
        if (template.contains("Response.java.vm")) {
            return commonCorePath + packagePath + File.separator + "core/ResponseEnum.java";
        }

        if (template.contains("PageQuery.java.vm")) {
            return commonCorePath + packagePath + File.separator + "domain/vo/PageQuery.java";
        }

        if (template.contains("Exception.java.vm")) {
            return commonCorePath + packagePath + File.separator + "exception/" + ProjectName + "Exception.java";
        }
        if (template.contains("ExceptionHandler.java.vm")) {
            return commonCorePath + packagePath + File.separator + "exception/GlobalExceptionHandler.java";
        }


        if (template.contains("DbConfig.java.vm")) {
            return commonDbPath + packagePath + File.separator + "config/DbConfig.java";
        }
        if (template.contains("PageVO.java.vm")) {
            return commonDbPath + packagePath + File.separator + "domain/vo/PageVO.java";
        }
        if (template.contains("BaseDO.java.vm")) {
            return commonDbPath + packagePath + File.separator + "domain/model/BaseDO.java";
        }
        return null;
    }

    private static String splitInnerName(String name) {
        name = name.replaceAll("\\.", "_");
        return name;
    }

    public static void main(String[] args) {
        Map<String, String> table = new HashMap<>();
        table.put("tableName", "dish");
        table.put("tableComment", "菜品表");
        List<Map<String, String>> columns = new ArrayList<>();
        Map<String, String> column = new HashMap<>();
        column.put("columnName", "id");
        column.put("dataType", "bigint");
        column.put("columnComment", "主键");
        column.put("extra", "");
        column.put("columnKey", "PRI");
        columns.add(column);
        Map<String, String> column2 = new HashMap<>();
        column2.put("columnName", "dish_name");
        column2.put("dataType", "varchar");
        column2.put("columnComment", "菜品名称");
        columns.add(column2);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        generatorCode(table, columns, zip, true);
        //保存zip文件
        IOUtils.closeQuietly(zip);
        //输出到文件
        try {
            IOUtils.write(outputStream.toByteArray(), new FileOutputStream("D:\\test.zip"));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
